<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width="800"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      layout="horizontal"
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 4 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 20 }, sm: { span: 24 } }"
    >
      <a-form-item label="icon:" name="icon">
        <a-input v-model:value="form.icon" type="hidden" />
        <a-upload list-type="picture-card" class="avatar-uploader" :headers="headers" :show-upload-list="false" :customRequest="uploadIcon">
          <img v-if="form.iconUrl" :src="form.iconUrl" alt="icon" id="iconUrl" />
          <div v-else>
            <div class="ant-upload-text">上传icon</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="主图:" name="file_id">
        <a-input v-model:value="form.file_id" type="hidden" />
        <a-upload
          list-type="picture-card"
          class="avatar-uploader"
          :headers="headers"
          :show-upload-list="false"
          :customRequest="uploadSeries"
        >
          <img v-if="imageUrl != ''" :src="imageUrl" alt="avatar" class="imageUrl" style="max-width: 600px" />
          <div v-else>
            <div class="ant-upload-text">上传主图</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="标题:" name="title">
        <a-input v-model:value="form.title" placeholder="请输入标题" maxLength="50" allow-clear autocomplete="off" />
      </a-form-item>
      <a-form-item label="英文标题:" name="etitle">
        <a-input v-model:value="form.etitle" placeholder="请输入标题" maxLength="50" allow-clear autocomplete="off" />
      </a-form-item>
      <a-form-item label="简介:" name="introduction">
        <a-textarea v-model:value="form.introduction" placeholder="请输入简介" maxLength="500" allow-clear autocomplete="off" :rows="4" />
      </a-form-item>
      <a-form-item label="排序:" name="sort">
        <a-input-number
          v-model:value="form.sort"
          placeholder="请输入排序"
          style="width: 100%"
          :min="0"
          :max="9999"
          allow-clear
          autocomplete="off"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { BusinessAreaApi } from '@/api/businessArea/BusinessAreaApi';
import { FileApi } from '@/api/FileApi';
import setting from '@/config/setting';

export default {
  name: 'BusinessAreaEdit',
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        file_id: [{ required: true, message: '请上传主图', type: 'string', trigger: 'blur' }],
        icon: [{ required: true, message: '请输入icon', type: 'string', trigger: 'blur' }],
        title: [{ required: true, message: '请输入标题', type: 'string', trigger: 'blur' }]
      },
      // 提交状态
      loading: false,
      // 上传文件时候要带header
      //图url
      imageUrl: '',
      // 上传文件时候要带header
      headers: {
        Authorization: setting.takeToken()
      },
      // 是否是修改
      isUpdate: false
    };
  },
  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        this.imageUrl = this.handleSrc(this.form);
        this.form.fileId = this.form.file_id;
        this.isUpdate = true;
      } else {
        this.form = {};
        this.imageUrl = '';
        this.isUpdate = false;
      }
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    }
  },
  methods: {
    /**
     * 处理image的src属性
     *
     * @author fengshuonan
     * @date 2021/5/28 15:19
     */
    handleSrc(record) {
      return `/api/wx/sysFileInfo/public/preview?fileId=${record.file_id}&token=${setting.takeToken()}`;
    },
    /**
     * 保存和编辑
     *
     * @author jizhongbao
     * @date 2022/01/10 15:07
     */
    async save() {
      console.log(this.form);
      // 校验表单
      await this.$refs.form.validate();

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = BusinessAreaApi.edit(this.form);
      } else {
        result = BusinessAreaApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          this.$message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 上传icon
     */
    uploadIcon(file) {
      this.loading = true;
      let formData = new FormData();
      formData.append('file', file.file);
      let uploadResult = FileApi.commonUpload('N', formData);
      uploadResult
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          this.$message.success(result.message);

          this.form.icon = result.data.fileId;
          this.form.iconUrl = result.data.fileUrl;
        })
        .catch(() => {
          this.loading = false;
        });
      return false;
    },
    /**
     * 上传主图
     */ uploadSeries(file) {
      console.log(13133);
      this.loading = true;
      let formData = new FormData();
      formData.append('file', file.file);
      let uploadResult = FileApi.commonUpload('N', formData);
      uploadResult
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          this.$message.success(result.message);

          this.form.file_id = result.data.fileId;
          this.form.fileId = result.data.fileId;
          this.imageUrl = result.data.fileUrl;
        })
        .catch(() => {
          this.loading = false;
        });
      return false;
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author jizhongbao
     * @date 2022/01/10 15:07
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  }
};
</script>
<style>
#iconUrl {
  width: 104px;
  height: 104px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>